const path = require("path");
const webpack = require("webpack");
const ejs = require("ejs");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { version } = require("./package.json");
//! 用于按需自动导入 element-plus 组件
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");

// 打包配置
const config = {
  mode: process.env.NODE_ENV, // 打包模式
  // 打包基础路径
  context: path.join(__dirname, "./src"),
  // 打包入口
  entry: {
    background: "./background.js",
    "popup/popup": "./popup/popup.js", // 注意多入口打包这里的属性会对应生成目录文件
    "options/options": "./options/options.js",
  },
  // 打包出口
  output: {
    path: path.join(__dirname, "./dist"), // 输出目录
    filename: "[name].js", // 输出文件(注意这里如果打包入口多个则不能写死)
  },
  devtool: false,
  resolve: {
    extensions: [".js", ".vue"], // 打包包含的后缀文件
  },
  stats: process.env.NODE_ENV === "development" ? "normal" : "errors-only", // 打包日志输出
  // 将第三方代码分割一个文件
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: "/vendors/vendors",
          chunks: "all",
        },
      },
    },
  },
  module: {
    // 规则配置
    rules: [
      {
        test: /\.vue$/, // vue-loader 进行编译对所有后缀 vue 文件
        loader: "vue-loader",
      },
      {
        test: /\.js$/, // 将 Es6+ 语法转换为 Es5 语法
        loader: "babel-loader",
        exclude: /node_modules/, // 忽略 node_modules 文件
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"], // 需要配合插件一起使用
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|ico)$/, // 处理图片资源
        loader: "file-loader",
        options: {
          // 文件名可以是字符串也可以是函数配置
          name() {
            if (process.env.NODE_ENV === "development") {
              return "[hash].[ext]";
            }
            return "[path][name].[ext]";
          },
          outputPath: "/images/", // 输出目录
          emitFile: true,
          esModule: false,
        },
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/, // 处理文字资源
        loader: "file-loader",
        options: {
          name: "[path][name].[ext]",
          outputPath: "/fonts/",
          emitFile: true,
          esModule: false,
        },
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(), // 清除之前打包生成文件
    new webpack.DefinePlugin({
      global: "window",
    }),
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].css", // 打包后提交样式文件名
    }),
    new CopyPlugin({
      patterns: [
        { from: "icons", to: "icons" },
        { from: "css", to: "css" },
        { from: "fonts", to: "fonts" },
        {
          from: "popup/popup.html",
          to: "popup/popup.html",
          transform(content) {
            // 通过 ejs 渲染模板注入参数
            return ejs.render(content.toString(), {
              ...process.env,
            });
          },
        },
        {
          from: "options/options.html",
          to: "options/options.html",
        },
        {
          from: "options/options.css",
          to: "options/options.css",
        },
        {
          from: "manifest.json",
          to: "manifest.json",
          transform: (content) => {
            const jsonContent = JSON.parse(content); // 获取到内容
            jsonContent.version = version; // 通过项目控制插件版本
            return JSON.stringify(jsonContent, null, 4); // 第三参数表述缩进空格
          },
        },
      ],
    }),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
};

// 生产环境添加全局变量
if (config.mode === "production") {
  config.plugins = (config.plugins || []).concat([
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify("production"),
      },
    }),
  ]);
}

//! 开发环境下开发谷歌重启插件(此处不进行使用)此插件依赖 webpack4 而此项目 webpack5
// 插件名称 webpack-extension-reloader

// if (process.env.HMR === "true") {
//   config.plugins = (config.plugins || []).concat([
//     new ExtensionReloader({
//       manifest: __dirname + "/src/manifest.json",
//     }),
//   ]);
// }

module.exports = config;
